﻿Imports ModuloFinanceiro
Imports ModuloEstoque
Imports VendasBLL
Imports VendasDAL
Imports EstoqueBLL
Public Class Teste
    Dim ObjBLL As New VendaBLL
    Dim ObjCliente As New ClientesBLL
    Dim ObjPeca As PECABLL
    Dim ObjServico As ServicoBLL
    Public Codigo, CodCliente, ProCodigo, Status As Integer
    Public Op, Operacao As String
#Region "Métodos"
    Sub CarregaCampos()
        ObjBLL = New VendaBLL(Codigo)
        LBCodigo.Text = "Código: " & ObjBLL.VenCodigo
        ObjCliente = New ClientesBLL(ObjBLL.CodCliente)
        DGVDados.DataSource = ObjBLL.RetItens(Codigo)
        CodCliente = ObjCliente.Codigo
        TXTCliente.Text = ObjCliente.Nome
        AtualizaValoreGrid()
        PNProdutos.Enabled = True
        PNOperacaoProduto.Enabled = True
        TSBLocalizarAgendamento.Visible = False
    End Sub
    Sub AtualizaValorProduto()
        Dim ValorTotal, ValorDesc, ValorUnitario As Decimal
        Dim Qtde As Integer

        If (Decimal.TryParse(TXTDesReais.Text.Replace("R$", ""), ValorDesc)) Then
        Else : ValorDesc = "0,00"
        End If

        If (Decimal.TryParse(TXTValUnitario.Text.Replace("R$", ""), ValorUnitario)) Then
        Else : ValorUnitario = "0,00"
        End If

        If (Integer.TryParse(TXTQuantidade.Text, Qtde)) And Qtde > 0 Then
        Else : Qtde = 1
        End If

        ValorTotal = ValorUnitario * Qtde
        If (ValorTotal > ValorDesc) Then
            ValorTotal = ValorTotal - ValorDesc
        Else : Throw New Exception("Desconto maior que valor total")
        End If

        If Status <> 10 Then
            If (Qtde <= Val(TXTQtdeDisponivel.Text)) Then
            Else : Throw New Exception("Quantidade indisponível")
            End If
        End If

        TXTQuantidade.Text = Qtde
        TXTDesReais.Text = ValorDesc
        TXTValTotal.Text = ValorTotal
        TXTValTotal.Text = FormatCurrency(TXTValTotal.Text)
        TXTDesReais.Text = FormatCurrency(TXTDesReais.Text)
    End Sub
    Sub AtualizaValoreGrid()

        Dim Total As Decimal = "0.00"
        Dim Desconto As Decimal = "0.00"
        Dim VlMaodeObra As Decimal = "0.00"
        For Each col As DataGridViewRow In DGVDados.Rows
            If col.Cells("sta_codigo").Value = 10 Then
                VlMaodeObra += col.Cells("itv_total").Value
            Else
                Total += col.Cells("itv_total").Value
            End If

            Desconto += col.Cells("itv_desconto").Value

        Next
        TXTVlDesconto.Text = Desconto
        TXTVlTotal.Text = (Total + VlMaodeObra) - Desconto
        TXTVlMaoObra.Text = VlMaodeObra
        TXTVlPeca.Text = Total
        TXTVlTotal.Text = FormatCurrency(TXTVlTotal.Text)
        TXTVlDesconto.Text = FormatCurrency(TXTVlDesconto.Text)
        TXTVlPeca.Text = FormatCurrency(TXTVlPeca.Text)
        TXTVlMaoObra.Text = FormatCurrency(TXTVlMaoObra.Text)
    End Sub
    Sub Limpa()
        TXTCliente.Text = ""
        TXTVlDesconto.Text = "R$ 0.00"
        TXTVlMaoObra.Text = "R$ 0.00"
        TXTVlPeca.Text = "R$ 0.00"
        TXTVlTotal.Text = "R$ 0.00"
        If DGVDados.DataSource Is Nothing Then
        Else
            Dim Dt As DataTable
            Dt = DGVDados.DataSource
            Dt.Rows.Clear()
            DGVDados.DataSource = Dt
        End If
        MTBDataEntrada.Text = Date.Now
        MTBHoraEntrada.Text = DateTime.Now.ToString("HH:mm")
        LBCodigo.Text = ""
        PNCLiente.Enabled = True
        PNProdutos.Enabled = False
        PNOperacaoProduto.Enabled = False

    End Sub
    Sub Salva()
        Try
            If (CodCliente > 0) Then
                Dim DataInicial As Nullable(Of DateTime)
                Dim Data As DateTime
                If DateTime.TryParse(MTBDataEntrada.Text & " " & MTBHoraEntrada.Text, Data) Then : DataInicial = Data
                Else : DataInicial = Nothing
                End If
                ObjBLL = New VendaBLL(Codigo, CodCliente, 4, CBFuncionario.SelectedValue, DataInicial, TXTObs.Text)
                If (Op = "I") Then
                    Codigo = ObjBLL.IAEVenda("I")
                    Op = "A"
                Else
                    ObjBLL.IAEVenda("A")
                End If
                ObjBLL = Nothing
            Else : Throw New Exception("Informe Cliente")
            End If
        Catch ex As Exception
            Throw
        End Try
    End Sub
    Sub CarregaProduto()
        Dim ValUnitario As Decimal
        Dim Desconto As Decimal
        Dim Total As Decimal
        Dim Qtde As Integer
        If Decimal.TryParse(TXTValUnitario.Text.Replace("R$", "").Replace(" ", ""), ValUnitario) Then
        End If
        If Decimal.TryParse(TXTDesReais.Text.Replace("R$", "").Replace(" ", ""), Desconto) Then
        End If
        If Decimal.TryParse(TXTValTotal.Text.Replace("R$", "").Replace(" ", ""), Total) Then
        End If
        If Integer.TryParse(TXTQuantidade.Text, Qtde) Then
        End If

        ObjBLL = New VendaBLL(ProCodigo, Qtde, ValUnitario, Desconto, Codigo, Total, Status)

    End Sub
    Sub LimpaProduto()
        TXTCodBarras.Text = ""
        TXTCodigo.Text = ""
        TXTDescricao.Text = ""
        TXTQuantidade.Text = ""
        TXTQtdeDisponivel.Text = ""
        TXTValUnitario.Text = "R$ 0.00"
        TXTDesReais.Text = "R$ 0.00"
        TXTValTotal.Text = "R$ 0.00"
        ProCodigo = 0
    End Sub
#End Region
#Region "Eventos"

#Region "Pintar datagridview"
    Private Sub DGVDados_RowPrePaint(sender As System.Object, e As System.Windows.Forms.DataGridViewRowPrePaintEventArgs)
        If DGVDados.Rows(e.RowIndex).Index Mod (2) = 1 Then
            DGVDados.Rows(e.RowIndex).DefaultCellStyle.BackColor = Color.Gainsboro
        End If
    End Sub
#End Region

#Region "DatagridView alterar"
    Private Sub DGVDados_CellDoubleClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs)
        TSBALterar_Click(Nothing, Nothing)
    End Sub
#End Region

#Region "DatagridView deletar"
    Private Sub DGVDados_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Delete) Then
            TSBExcluir_Click(Nothing, Nothing)
        End If
    End Sub
#End Region

#Region "DatagridView alterar"
    Private Sub DGVDados_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = Convert.ToChar(Keys.Return) Then
            TSBALterar_Click(Nothing, Nothing)
        End If
    End Sub
#End Region

#Region "Fechar formulário com esc"

    Private Sub OrdemServicoFRM_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs)
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
#End Region

#Region "TextBox Quantidade"
    Private Sub TXTQuantidade_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TXTQuantidade.KeyPress
        If Not Char.IsNumber(e.KeyChar) And Not e.KeyChar = vbBack Then
            e.Handled = True
        End If
        If e.KeyChar = Convert.ToChar(Keys.Return) Then
            TXTDesReais.Select()
        End If

    End Sub

    Private Sub TXTQuantidade_MouseUp(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles TXTQuantidade.MouseUp
        TXTQuantidade.SelectAll()
    End Sub

    Private Sub TXTQuantidade_Leave(sender As System.Object, e As System.EventArgs) Handles TXTQuantidade.Leave
        Try
            AtualizaValorProduto()
            TXTDesReais.Focus()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            TXTQuantidade.Text = 1
        End Try

    End Sub

    Private Sub TXTQuantidade_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles TXTQuantidade.KeyDown
        If (e.KeyCode = Keys.Enter) Then
            SendKeys.Send("{TAB}")
        End If
    End Sub
#End Region

#Region "TextBox Desconto (R$)"
    Private Sub TXTDesReais_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TXTDesReais.KeyPress
        If Not Char.IsNumber(e.KeyChar) And Not e.KeyChar = vbBack Then
            e.Handled = True
        End If
        If (TXTDesReais.Text.Contains(",") = False And e.KeyChar = ",") Then
            e.Handled = False
        End If
        If e.KeyChar = Convert.ToChar(Keys.Return) Then
            TSBSalvar.Select()
            AtualizaValorProduto()
        End If
    End Sub

    Private Sub TXTDesReais_MouseUp(sender As System.Object, e As System.Windows.Forms.MouseEventArgs) Handles TXTDesReais.MouseUp
        TXTDesReais.SelectAll()
    End Sub

    Private Sub TXTDesReais_Leave(sender As System.Object, e As System.EventArgs) Handles TXTDesReais.Leave
        Try
            AtualizaValorProduto()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            TXTDesReais.Text = "R$ 0,00"
        End Try

    End Sub
#End Region

#Region "Fechar formulário com esc"
    Private Sub VendaFRM_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown
        If (e.KeyCode = Keys.Escape) Then
            Me.Close()
        End If
    End Sub
#End Region
#End Region
#Region "Códigos não implementados"
    '#Region "Carregar Dinamicamente"
    '    Public Sub carregadinamico()
    '        Try
    '            Dim dt, dt2 As New DataTable
    '            dt = ObjBLL.buscar("", 9)
    '            'dt2 = ObjBLL.buscar("", 8)
    '            'Dim test As Integer
    '            For Each item As DataRow In dt.Rows
    '                If (Val(item("fun_codigo").ToString) > 0) Then
    '                    tvmenu.Nodes.Add(item("fun_nome").ToString, item("fun_nome"))
    '                End If
    '            Next
    '            'For Each subitem As DataRow In dt.Rows
    '            '    test = (Val(subitem("car_codigo").ToString))
    '            '    test = test - 1
    '            '    tvmenu.Nodes(test).Nodes.Add(subitem("fun_codigo").ToString, subitem("fun_nome"))
    '            'Next
    '            'tvmenu.ExpandAll()
    '            tvmenu.TopNode = tvmenu.Nodes(0)
    '        Catch ex As Exception
    '            Throw
    '        End Try
    '    End Sub
    '#End Region

    '#Region "TVMenu_AfterCheck"
    '    Private Sub tvmenu_AfterCheck(sender As System.Object, e As System.Windows.Forms.TreeViewEventArgs)
    '        If (e.Node.Checked = True) Then
    '            For Each item As TreeNode In e.Node.Nodes
    '                item.Checked = True
    '            Next
    '        Else
    '            For Each item As TreeNode In e.Node.Nodes
    '                item.Checked = False
    '            Next
    '        End If
    '    End Sub
    '#End Region
#End Region


#Region "Load"

    Private Sub VendaFRM_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        objconexao.carregaCombo(CBFuncionario, "Vendas.Ofi_Funcionario", "fun_codigo", "fun_nome", "sta_codigo < 3", "fun_nome")
        CBStatus.SelectedIndex = 0
        TSBIncluir.Enabled = False
        TSBALterar.Enabled = False
        TSBIncluir.Enabled = False
        Limpa()
        If (Op = "I") Then
            TSBLocalizarAgendamento.Visible = True
            Codigo = 0
            CodCliente = 0
        Else
            CarregaCampos()
        End If
    End Sub
#End Region

#Region "Botões"

#Region "Voltar"
    Private Sub TSBVoltar_Click(sender As System.Object, e As System.EventArgs) Handles TSBVoltar.Click
        Me.Close()
    End Sub
#End Region

#Region "Salvar"
    Private Sub TSBSalvar_Click(sender As System.Object, e As System.EventArgs) Handles TSBSalvar.Click
        Try
            Salva()
            MessageBox.Show("Venda gravada com sucesso!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
            Me.Close()
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Sub

#End Region

#Region "Incluir"
    Private Sub TSBIncluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBIncluir.Click
        Try
            If (ProCodigo > 0) Then
                CarregaProduto()
                ObjBLL.IAEItens(Operacao)
                DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                LimpaProduto()
                TSBIncluir.Enabled = False
                TSBALterar.Enabled = True
                TSBExcluir.Enabled = True
                GBPreco.Enabled = False
            Else : Throw New Exception("Escolha um produto/serviço")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub
#End Region

#Region "Alterar"
    Private Sub TSBALterar_Click(sender As System.Object, e As System.EventArgs) Handles TSBALterar.Click
        Try
            Dim cod As Integer = 0
            Dim indice As Integer = -1
            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pro_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                ProCodigo = DGVDados.Rows(indice).Cells("pro_codigo").Value
                ObjBLL = New VendaBLL(Codigo, ProCodigo)
                ObjBLL.RetItem()
                TXTValUnitario.Text = ObjBLL.ValorUnitario
                TXTQuantidade.Text = ObjBLL.Qtde
                TXTDesReais.Text = ObjBLL.Desconto
                If ObjBLL.CodStatus = 10 Then
                    ObjServico = New ServicoBLL(ObjBLL.ProCodigo)
                    TXTCodBarras.Text = ""
                    TXTDescricao.Text = ObjServico.pro_descricao
                    TXTCodigo.Text = ObjServico.pro_codigo
                    ProCodigo = ObjServico.pro_codigo
                    TXTValUnitario.Text = ObjServico.pro_precovenda
                    TXTQtdeDisponivel.Text = ""
                    TXTQuantidade.Text = ObjBLL.Qtde
                    TXTDesReais.Text = ObjBLL.Desconto
                    AtualizaValorProduto()
                    ObjServico = Nothing
                Else
                    ObjPeca = New PECABLL()
                    ObjPeca.carregaproduto(ProCodigo)
                    TXTCodBarras.Text = ObjPeca.pec_codbarra
                    TXTDescricao.Text = ObjPeca.pro_descricao
                    TXTCodigo.Text = ObjPeca.pec_codigo
                    ProCodigo = ObjPeca.pro_codigo
                    TXTValUnitario.Text = ObjPeca.pec_valorunitario
                    TXTQtdeDisponivel.Text = (ObjPeca.pec_qtde + ObjBLL.Qtde)
                    TXTQuantidade.Text = ObjBLL.Qtde
                    TXTDesReais.Text = ObjBLL.Desconto
                    AtualizaValorProduto()
                    ObjPeca = Nothing
                End If
                AtualizaValorProduto()
                Operacao = "A"
                ObjBLL.Limpar()
                TSBIncluir.Enabled = True
                TSBALterar.Enabled = False
                TSBExcluir.Enabled = False
                GBPreco.Enabled = True
                BTNLocalizarDecsricao.Enabled = False
            Else : Throw New Exception("Selecione o produto/serviço a ser excluido")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Finally

        End Try
    End Sub
#End Region

#Region "Excluir"
    Private Sub TSBExcluir_Click(sender As System.Object, e As System.EventArgs) Handles TSBExcluir.Click
        Try
            Dim cod As Integer = 0
            Dim indice As Integer = -1
            For Each linha As DataGridViewRow In DGVDados.SelectedRows
                If (Not linha.Cells("pro_codigo") Is Nothing) Then
                    indice = linha.Index
                End If
            Next
            If (indice <> -1) Then
                If MessageBox.Show("Confirma exclusão do produto/serviço: " & DGVDados.Rows(indice).Cells("pro_descricao").Value.ToString() & " ?", "", MessageBoxButtons.YesNo) = vbYes Then
                    Salva()
                    ObjBLL = New VendaBLL(Codigo, DGVDados.Rows(indice).Cells("pro_codigo").Value)
                    ObjBLL.IAEItens("E")
                    DGVDados.DataSource = ObjBLL.RetItens(Codigo)
                    AtualizaValoreGrid()
                End If
            Else : Throw New Exception("Selecione o produto/serviço a ser excluido")
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Information)
        Finally
        End Try
    End Sub
#End Region
#End Region


    Private Sub BTNLocalizarCliente_Click(sender As System.Object, e As System.EventArgs) Handles BTNLocalizarCliente.Click
        Dim ObjCC As New ConsultaClientesFRM
        ObjCC.tipo = "ret"
        ObjCC.ShowDialog()
        If (Not IsNothing(ObjCC.ObjC)) Then
            Dim ObjCliente As New ClientesBLL
            ObjCliente = ObjCC.ObjC
            TXTCliente.Text = ObjCliente.Nome
            CodCliente = ObjCliente.Codigo
            ObjCliente = Nothing
            Salva()
            PNProdutos.Enabled = True
            PNOperacaoProduto.Enabled = True
            TSBLocalizarAgendamento.Visible = False
        End If
    End Sub

    Private Sub BTNLocalizarDecsricao_Click(sender As System.Object, e As System.EventArgs) Handles BTNLocalizarDecsricao.Click
        Dim ObjC As New PecaProdutoCON
        ObjC.Tipo = "ret"
        ObjC.ShowDialog()
        If (Not IsNothing(ObjC.ObjP)) Then
            TXTCodBarras.Text = ObjC.ObjP.pec_codbarra
            TXTDescricao.Text = ObjC.ObjP.pro_descricao
            TXTCodigo.Text = ObjC.ObjP.pec_codigo
            ProCodigo = ObjC.ObjP.pro_codigo
            TXTValUnitario.Text = ObjC.ObjP.pec_valorunitario
            TXTQtdeDisponivel.Text = ObjC.ObjP.pec_qtde
            AtualizaValorProduto()
            ObjC.ObjP = Nothing
            Status = 11
            TSBIncluir.Enabled = True
            TSBALterar.Enabled = False
            TSBExcluir.Enabled = False
            GBPreco.Enabled = True
            Operacao = "I"
        ElseIf (Not IsNothing(ObjC.ObjS)) Then
            TXTCodBarras.Text = ""
            TXTDescricao.Text = ObjC.ObjS.pro_descricao
            TXTCodigo.Text = ObjC.ObjS.pro_codigo
            ProCodigo = ObjC.ObjS.pro_codigo
            TXTValUnitario.Text = ObjC.ObjS.pro_precovenda
            TXTQtdeDisponivel.Text = ""
            AtualizaValorProduto()
            ObjC.ObjS = Nothing
            Status = 10
            TSBIncluir.Enabled = True
            TSBALterar.Enabled = False
            TSBExcluir.Enabled = False
            GBPreco.Enabled = True
            Operacao = "I"
        End If
    End Sub
End Class